import $var from "./var.js";
import $skip from "./skip.js";
import $fun from "./fun.js";
import $tools from "./tools.js";
import request from "./request.js";
import s from '@/js_sdk/plus-websocket/index.js'
// #ifdef APP-PLUS
Object.assign(uni, s)
// #endif
var $socket = {
	task: {},
	client_id: '',
	init(params, type) {
		type = type || 'default';
		if ($socket.task[type]) {
			console.log('socket 重复连接，直接返回对象');
			return $socket.task[type];
		}
		//创建连接
		let authInfo = request.getAuthInfo();
		let urlParams = $tools.getUrlParamsToString(authInfo);
		console.log(urlParams)
		$socket.task[type] = s.connectSocket({
			url: 'ws://127.0.0.1:9500' + urlParams,
			header: {
				'content-type': 'application/json',
				'abcd': 'abcd',
			},
			method: 'GET',
			success(r) {
				// console.log('socket 创建成功')
				s.onSocketOpen(r => {
					// console.log('socket 链接成功', r);
				});
				s.onSocketMessage(r => {
					let data = r.data;
					data = JSON.parse(r.data);
					// console.log('socket 接收信息', data);
					if (params.onMsg) {
						params.onMsg(data);
					}
				});
				s.onSocketError(r => {
					console.log('socket 错误', r);
				});
				s.onSocketClose(r => {
					console.log('socket 关闭', r);
				});
			},
			fail(r) {
				console.log(r)
			},
		});
	},
	send(data, type) {
		type = type || 'default';
		if (!$socket.task[type]) {
			console.log('socket 对象不存在');
			return;
		}
		if (typeof data == 'object') {
			data = JSON.stringify(data);
		} else if (typeof data != 'string') {
			data = data.toString();
		}
		$socket.task[type].send({
			data: data
		})
		// console.log('socket 发送信息',data);
	},
	close(type) {
		type = type || 'default';
		if (!$socket.task[type]) {
			console.log('socket 对象不存在');
			return;
		}
		$socket.task[type].close()
	}
};
export default $socket;